package com.huo.deque;


import java.util.ArrayList;
import java.util.Arrays;

public class ArrayDeque<E> implements Deque<E> {
    /**
     * 数组
     */
    transient Object[] elementData;
    /**
     * 大小
     */
    private int size;
    /**
     * 容量
     */
    private int capacity;


    public ArrayDeque(int capacity) {
        this.capacity = capacity;
        elementData = new Object[capacity];
    }


    @Override
    public void push(E e) {
        if (isFull()) {
            throw new RuntimeException("队列满！无法加入数据");
        }
        elementData[size++] = e;
    }

    @Override
    public E pop() {
        if (isEmpty()) {
            throw new ArrayIndexOutOfBoundsException("队列为空，无法取数据");
        }

        E e = (E) elementData[0];
        /**
         * 要删除队列首一个元素的时候，之后的元素都要向前推移，然后size--
         *  不是空的话，建立新数组，把旧数组的内容复制到新数组，但是这样效率低
         */

        if (!isEmpty()) {
            Object[] newEelementData = new Object[capacity];
            //下标为0的pop了，从第一个开始复制
            for (int i = 1; i < size; i++) {
                if (elementData[i] != null) {
                    newEelementData[i - 1] = elementData[i];
                }
            }
            elementData = newEelementData;
        }
        size--;
        return e;
    }


    @Override
    public boolean isFull() {
        return size == capacity;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public void showDequeData() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i < size; i++) {
            sb.append(elementData[i % capacity]);
            sb.append(",");
        }
        if (!sb.toString().equals("[")) {
            sb.deleteCharAt(sb.length() - 1);
        }
        sb.append("]");
        System.out.println(sb.toString());
    }

    public static void main(String[] args) {
        ArrayDeque<String> s = new ArrayDeque<>(10);
        s.push("我");
        s.push("是");
        s.push("你");
        s.push("1");
        s.push("2");
        s.push("3");
        s.push("4");
        s.showDequeData();
        s.pop();
        s.showDequeData();
        s.pop();
        s.showDequeData();
        s.pop();
        s.showDequeData();
        s.pop();
        s.showDequeData();
    }

}
